<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Controller\redirect;
use think\Session;

class login extends Controller
{
    /**
     * 用户登录页面
     *
     * @return \think\Response
     */
    public function index()
    {
        // dump(Session::get('register_name'));die;
        if(!empty(Session::get('register_name'))){
            echo "<script>alert('注册成功');</script>";
            Session::delete('register_name');
            return view('index');   
        }else{
            return view('index');               
        }
    }

    /**
     * 提交登录
     *
     * @return \think\Response
     */
    public function login(Request $Request,$username,$password)
    {
        $data = DB::name('user')->where('user_name',$username)->find();
        // dump($data['password'] == MD5($password));die;
        if(!empty($data) || $data['password'] == MD5($password)) 
        {
            Session::set('user_name',$data['user_name']);
            // return view('index/Index');
            $this->redirect('index/Index/index');
        }else{
            echo "<script>alert('用户还没有注册');</script>";
            return view('index');
        }
    }

    /**
     * 用户注册页面
     *
     * @return \think\Response
     */
    public function register()
    {
        // echo 'register';die;
        return view('register');
    }

   /**
     * 提交注册
     *
     * @return \think\Response
     */
    public function register_s(Request $Request,$username,$password,$passwords)
    {
        $data = Db::name('user')->where('user_name',$username)->find();
        if($username != null && $password != null && $passwords != null && $password == $passwords)
        {
            if(empty($data)){
                $pass = MD5($password);
                $list = ['user_name'=>$username,'password'=>$pass];
                $status = DB::name('user')->insert($list);
                if($status == 1)
                {
                    Session::set('register_name',$list);
                    $this->redirect('index/Login/index'); 
                }
            }else{
                echo "<script>alert('用户已经存在');</script>";
                return view('register');
            }
        }else if($password != $passwords){
            echo "<script>alert('密码不一致');</script>";
            return view('register'); 
        }else{
            echo "<script>alert('不能为空');</script>";
            return view('register');            
        }
    }

    /** 
     * 注销登录
    */
    public function logout()
    {
        Session::delete('user_name');
        return view('index/index');
    }
}
